package com.enjoyor.health.HGPT.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * 加密解密
 * @author Zhu Min
 * @date 2023/10/19 10:33
 */
public class EncryptUtil {

    public static void main(String args[]) throws Exception {
        byte[] cipherText = encrypt("Testing AES/CBC/PKCS5PADDING stuff from Java and with JavaScript - some random text".getBytes(), "5de9b78814ad6da9ead19e6ba022c80d".getBytes()); // 32 length Key
        System.out.println(new String(cipherText));
        byte[] origText = decrypt(new String(cipherText).getBytes(), "5de9b78814ad6da9ead19e6ba022c80d".getBytes());
        System.out.println(new String(origText));
    }

    public static byte[] encrypt(byte[] plainTextData, byte[] secretKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

            byte[] dataBytes = plainTextData;
            int plaintextLength = dataBytes.length;
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(secretKey, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, keyspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new String(Base64.getEncoder().encode(encrypted)).getBytes();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] decrypt(byte[] cipherTextData, byte[] secretKey) {
        try {
            byte[] encrypted = Base64.getDecoder().decode(cipherTextData);

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            SecretKeySpec keyspec = new SecretKeySpec(secretKey, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keyspec);

            byte[] original = cipher.doFinal(encrypted);
            String originalString = new String(original);
            return originalString.getBytes();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

